package com.ficv.tucanalmovil;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.ficv.tucanalmovil.R;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings.Secure;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class DisplayMessageActivity extends Activity {

	LocationManager locationManager ;
	Location lastLocation;
	Empresa e;
	
	
	public Location getLastLocation() {
		return lastLocation;
	}

	public void setLastLocation(Location lastLocation) {
		this.lastLocation = lastLocation;
	}

	private final LocationListener listener = new LocationListener() {

	    @Override
	    public void onLocationChanged(Location location) {
	        // A new location update is received.  Do something useful with it.  In this case,
	        // we're sending the update to a handler which then updates the UI with the new
	        // location.
	    	
	    	try {
		    	lastLocation=location;
		 	    Log.v("lastLocation: ",lastLocation==null?"null":lastLocation.toString());
	
				String androidId=Secure.getString(getContentResolver(), Secure.ANDROID_ID);
			
				String url = Utils.getUrlContent(MainActivity.URL_BASE) + "contact?androidId=" + androidId + "&medio=" + lastLocation.toString();
	
				Utils.getUrlContent(url);
	    	} catch(Throwable e) {
	    		Log.v("ERROR: ", e.getMessage());
	        }
	    }
	    
		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub
			
		}
	  
	};
	public int PICK_CONTACT=1001;


	 WebView myWebView;
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_display_message);
//        getActionBar().setDisplayHomeAsUpEnabled(true);
        // Get the message from the intent
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//
//        // Create the text view
//        TextView textView = new TextView(this);
//        textView.setTextSize(40);
//        textView.setText(message);
//https://getfirebug.com/firstrun#Firebug%201.10.4
//        // Set the text view as the activity layout
//        setContentView(textView);
        
 	    //locationManager =    (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
 		 //lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		 //lastLocation=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

 	    Log.v("lastLocationnull",lastLocation==null?"null":lastLocation.toString());
 		 
        //myWebView = (WebView) findViewById(R.id.webview);
    	
        if(message!=null) e = getEmpresa(message.trim());
    	if(e==null) {
        	e = new Empresa();
        	e.setImgUrl("japon.jpg");
        	e.setDescription("Fidelice a sus clientes con una aplicación de contacto como ésta. Consulte personalizaciones.");
        	e.setPhone("668868055");
        	e.setEmail("francisco.isaac@gmail.com");
        	e.setLocation("Madrid");
        	e.setWeb("https://sites.google.com/site/tucanalmovil");
    	}

        myWebView = new WebView(this);
        myWebView.addJavascriptInterface(new JavaScriptInterface(this,myWebView,e), "Android");
        myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        myWebView.setWebViewClient(new MyWebViewClient());
                
        //myWebView.loadUrl("http://www.uco.es/~i42cavif/android/test2.html");
        //myWebView.loadUrl("http://192.168.2.102:8080/baseforandroid/reaseguradors?form");
        

        getSize();
        loadUrl();
        Log.v("VIEW","cargando de verdad code = " + message);
        setContentView(myWebView);
        
        
//        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
//                10000,          // 100-second interval.
//                100,             // 100 meters.
//                listener);
        
       
        	
        	
    }

	private void getSize() {
		Display display = getWindowManager().getDefaultDisplay();
        
        width = display.getWidth();
        height = 50; //display.getHeight()/5;
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_display_message, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.content:
            	
                NavUtils.navigateUpFromSameTask(this);
                return true;
            case R.id.menu_avisos:
            	 Intent intent = new Intent(this, AvisoActivity.class);
            	 startActivity(intent);
                return true;    
        }
        return super.onOptionsItemSelected(item);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
        	Log.v("mitag", url);
           // if (Uri.parse(url).getHost().equals("www.uco.es")) {
                // This is my web site, so do not override; let my WebView load the page
        	view.loadUrl(url);
    
        	return true;
           // }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            //startActivity(intent);
            //return true;
        }
        
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                    view.loadUrl("file:///android_asset/index.html"); // load page without internal link

                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                    view.loadUrl("file:///android_asset/index.html?logo=" + e.getImgUrl() + "&desc=" + e.getDescription() + "&width=" + width);
          }


       }


        
    

	String name = null;
    String phoneNumber=null;
    String emailAddress=null;
    String poBox      =null;
    String street     =null;
    String city       =null;
    String state      =null;
    String postalCode =null;
    String country    =null;
    String type            =null;
    
    public void onActivityResult(int requestCode, int resultCode, Intent intent) 
    {

      if (requestCode == PICK_CONTACT)
      {         
        getContactInfo(intent);         
        Toast.makeText(this, name + ", " + phoneNumber + ", " + emailAddress , Toast.LENGTH_SHORT).show();
      }
    }

    protected void getContactInfo(Intent intent)
    {

        
       Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);      
       while (cursor.moveToNext()) 
       {           
           String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
           name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

           
           String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

           if ( hasPhone.equalsIgnoreCase("1"))
               hasPhone = "true";
           else
               hasPhone = "false" ;

           if (Boolean.parseBoolean(hasPhone)) 
           {
            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
            while (phones.moveToNext()) 
            {
              phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phones.close();
           }

           // Find Email Addresses
           Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
           while (emails.moveToNext()) 
           {
            emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
           }
           emails.close();

        Cursor address = getContentResolver().query(
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
                    null, null);
        while (address.moveToNext()) 
        { 
          // These are all private class variables, don't forget to create them.
          poBox      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
          street     = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
          city       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
          state      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
          postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
          country    = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
          type       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
        }  //address.moveToNext()   
      }  //while (cursor.moveToNext())        
       cursor.close();
    }//getContactInfo

    protected Empresa getEmpresa(String code) 
	{
		try 
		{
			// The URL for making the GET request
			//final String url = "http://192.168.2.102/" + code + ".xml";
			
				
			String url = Utils.getUrlContent(MainActivity.URL_BASE) + "emp?code=" + code;

			
			// Set the Accept header for "application/xml"
			HttpHeaders requestHeaders = new HttpHeaders();
			List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
			acceptableMediaTypes.add(MediaType.APPLICATION_XML);
			requestHeaders.setAccept(acceptableMediaTypes);
			
			// Populate the headers in an HttpEntity object to use for the request
			HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
			
			// Create a new RestTemplate instance
			RestTemplate restTemplate = new RestTemplate();
			
			// Perform the HTTP GET request
			ResponseEntity<Empresa> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Empresa.class);
			
			// Return the list of states
			Empresa empresa = responseEntity.getBody();

			return empresa;
		} 
		catch(Exception e) 
		{
			Log.e("TAG", e.getMessage(), e);
		} 
		
		return null;
	}
    
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        getSize();
         loadUrl();
        //Toast.makeText(this, width + ", " + height, Toast.LENGTH_LONG).show();
      }
    
    int width;
    int height;
    
//    @Override
//    public void onStart() {
//    	super.onStart();
//     
//        //Toast.makeText(this, width + ", " + height, Toast.LENGTH_LONG).show();
//    }

	private void loadUrl() {
		if(e.getName()!=null) {
        	//myWebView.loadUrl("file:///android_asset/index.html?logo=" + e.getImgUrl() + "&desc=" + e.getDesc() + "&width=" + width);
        } else {
        	Toast.makeText(this, "Codigo " + getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE) +" no accesible. Mostrando contacto con tucanalmovil", Toast.LENGTH_LONG).show();
        	//myWebView.loadUrl("file:///android_asset/nocode.html");
        	

        }
		

//		List<NameValuePair> params = new LinkedList<NameValuePair>();
//
//
//	        params.add(new BasicNameValuePair("logo", e.getImgUrl()));
//	        params.add(new BasicNameValuePair("desc", e.getDescription()));
//	        params.add(new BasicNameValuePair("width",String.valueOf(width)));
//
//	    String paramString = URLEncodedUtils.format(params, "utf-8");

		
		//myWebView.loadUrl("file:///android_asset/index.html?logo=" + e.getImgUrl() + "&desc=" + e.getDesc() + "&width=" + width);
	
//		myWebView.addEventListener("beforeload", function(e) {
//		    webView.evalJS("var desc="+ e.getDesc() +";");
//		    webView.evalJS("var logo="+ e.getImgUrl()+";");
//		    webView.evalJS("var widt="+ width +";");
//		});
		
		myWebView.loadUrl("file:///android_asset/index.html");	
		
		
		
		//String yourURI="file:///android_asset/index.html";
		//Uri path = Uri.parse("android.resource://com.ficv.tucanalmovil/raw/index");
		//yourURI = getRealPathFromURI(Uri.parse(yourURI));
		//myWebView.loadUrl(uri.);
		//myWebView.loadUrl("?logo=" + e.getImgUrl() + "&desc=" + e.getDesc() + "&width=" + width);
		//Got the Real Path Of the File

	}
  
	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	private String getRealPathFromURI(Uri contentURI) {
		  Cursor cursor = getContentResolver().query(contentURI, null, null, null, null); 
		  cursor.moveToFirst(); 
		  int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
		  return cursor.getString(idx); 
		}
}
